package org.shiftone.cdep.store;

import org.apache.log4j.Logger;
import org.shiftone.cdep.util.JDBCUtil;
import org.shiftone.cdep.store.AbstractStoreManager;

import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.PreparedStatement;

public class SqlServerStoreManager extends AbstractStoreManager
{
    public static Logger LOG = Logger.getLogger(SqlServerStoreManager.class);

    public SqlServerStoreManager()
    {
    }

    protected String prepareInsertQuery(String methodName, String query, boolean generateKey)
    {
        return query + " SELECT @@IDENTITY";
    }

    protected String prepareUpdateQuery(String methodName, String query)
    {
        return query;
    }

    protected String prepareSelectQuery(String methodName, String query)
    {
        return query;
    }

    protected String prepareDeleteQuery(String methodName, String query)
    {
        return query;
    }

    protected int executeInsert(PreparedStatement stmt, boolean generateKey) throws SQLException
    {
        ResultSet rs = stmt.executeQuery();

        try
        {
            if (rs.next())
            {
                return rs.getInt(1);
            }

            throw new SQLException("Insert failed.");
        }
        finally
        {
            JDBCUtil.close(stmt);
        }
    }

    protected void executeDelete(PreparedStatement stmt) throws SQLException
    {
        if (stmt.executeUpdate() < 1)
        {
            throw new SQLException("Failed to update any rows");
        }
    }

    protected ResultSet executeSelect(PreparedStatement stmt) throws SQLException
    {
        return stmt.executeQuery();
    }

    protected void executeUpdate(PreparedStatement stmt) throws SQLException
    {
        if (stmt.executeUpdate() < 1)
        {
            throw new SQLException("Failed to update any rows");
        }
    }
}
